<template>
  <div class="wrapper">
    <el-scrollbar style="height: 100%">
      <el-row class="row">
        <el-upload
          action="https://upload-z1.qiniup.com"
          multiple
          :limit="999"
          :data="qiNiuData"
          list-type="picture-card"
          accept="image/*"
          :on-preview="handlePictureCardPreview"
          :on-remove="handleRemove"
          :before-upload="beforeUpload"
          :on-error="uploadError"
          :on-success="uploadSuccess"
          :on-exceed="uploadExceed"
          ref="upload"
          :file-list="imgList"
        >
          <i class="el-icon-plus"></i>
        </el-upload>

        <el-dialog :visible.sync="dialogVisible" append-to-body>
          <img width="100%" :src="dialogImageUrl" alt="" />
        </el-dialog>
      </el-row>
    </el-scrollbar>
  </div>
</template>

<script>
import {getQiNiuToken} from '../../../api/photo'
import {messageError, messageWarning, notifyError} from '../../../utils/message'
import {fmtDate, getNowTime} from '../../../utils/DateUtil'

export default {
  name: 'UploadPhoto',
  props: ['albumId'],
  created() {
    this.getQiNiuToken()
  },
  data() {
    return {
      qiNiuToken: null,
      qiNiuData: {token: '', key: '', 'x:userId': '', 'x:albumId': this.albumId, 'x:lastModifiedDate': ''},
      dialogImageUrl: '',
      dialogVisible: false,
      imgList: []
    }
  },
  methods: {
    beforeUpload(file) {
      this.qiNiuData.token = this.qiNiuToken
      this.qiNiuData.key = this.$store.getters.name + '/photo/' + getNowTime() + '_' + file.name
      this.qiNiuData['x:userId'] = this.$store.getters.userId
      this.qiNiuData['x:lastModifiedDate'] = fmtDate(file.lastModifiedDate)
    },
    handleRemove(file, fileList) {},
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    clearUpdateImage() {
      this.$refs.upload.clearFiles()
    },
    getQiNiuToken() {
      getQiNiuToken()
        .then(response => {
          if (response.code === 0) {
            this.qiNiuToken = response.data.token
            return
          }
          throw response
        })
        .catch(err => {
          messageError('获取上传服务器token失败')
        })
    },
    uploadSuccess() {},
    uploadError(err, file, fileList) {
      notifyError(file.name + '上传失败')
    },
    uploadExceed() {
      messageWarning('一次最多上传99个文件')
    }
  }
}
</script>

<style scoped>
.wrapper {
  height: 600px;
}
</style>
